package com.blockchain.controller;


import com.blockchain.model.Follow;
import com.blockchain.model.User;
import com.blockchain.repository.FollowRepository;
import com.blockchain.repository.UserRepository;
import com.blockchain.service.UserService;
import com.blockchain.service.dto.FollowDTO;
import com.blockchain.service.dto.UserDTO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FollowRepository followRepository;
    @Autowired
    private UserRepository userRepository;
    @GetMapping("/userinfo")
    public UserDTO getUserInfo(@RequestParam("username") String username){
        User user=userRepository.findByUsername(username);
        UserDTO userDTO=new UserDTO();
        userDTO.setUsername(user.getUsername());
        userDTO.setAvatarUrl(user.getAvatarUrl());
        userDTO.setSex(user.getSex());
        userDTO.setIntroduce(user.getIntroduce());
        userDTO.setUser_id(user.getUserId());
        userDTO.setBirthday(user.getBirthday());
        return userDTO;
    }
    @GetMapping("/api/all_userinfo")
    public UserDTO getAllUserInfo() {
        // 从请求中获取解析后令牌中的用户信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Claims claims = (Claims) request.getAttribute("claims");
        if (claims != null) {
            int user_id =(int)claims.get("user_id");
            UserDTO userDTO=new UserDTO();
            User user=userRepository.findByUserId(user_id);
            userDTO.setUser_id(user.getUserId());
            userDTO.setBirthday(user.getBirthday());
            userDTO.setAvatarUrl(user.getAvatarUrl());
            userDTO.setSex(user.getSex());
            userDTO.setEmail(user.getEmail());
            userDTO.setUsername(user.getUsername());
            userDTO.setIntroduce(user.getIntroduce());
            // 如果找到用户，直接返回用户对象
            return userDTO;
        } else {
            // 如果未能获取用户信息，返回空对象或者其他提示信息，根据实际需求来定
            return null;
        }
    }
    @PostMapping("/api/all_userinfo")
    public ResponseEntity<String> updateUserInfo(@RequestBody UserDTO updateUser){
        try {
            System.out.println(updateUser.getUser_id());
            User existingUser=userRepository.findByUserId(updateUser.getUser_id());
            if(existingUser !=null)
            {
                existingUser.setBirthday(updateUser.getBirthday());
                existingUser.setIntroduce(updateUser.getIntroduce());
                existingUser.setSex(updateUser.getSex());
                if(updateUser.getUsername()!=null){
                User user_try=userRepository.findByUsername(updateUser.getUsername());
                if(user_try!=null){
                    return ResponseEntity.ok().body("用户名已存在，修改失败");
                }else {
                existingUser.setUsername(updateUser.getUsername());
                    }
                }
                userRepository.save(existingUser);
                return ResponseEntity.ok().body("用户信息更新完成");
            }else {
                return ResponseEntity.ok().body("用户不存在");
            }

        } catch (Exception e) {
            return ResponseEntity.ok().body("更新用户信息失败: " + e.getMessage());
        }
    }
    @PostMapping("/api/avatar_upload")
    public ResponseEntity<String> updateAvatar(@RequestBody UserDTO userDTO){
        try {
            User user1=userRepository.findByUserId(userDTO.getUser_id());
            if(user1!=null) {
                user1.setAvatarUrl(userDTO.getAvatarUrl());
                userRepository.save(user1);
                return ResponseEntity.ok().body("用户头像更新完成");
            }else {
                return ResponseEntity.ok().body("用户不存在");
            }
        }catch (Exception e){
            return ResponseEntity.ok().body("更新用户信息失败"+e.getMessage());
        }
    }
    @GetMapping("/api/get_password")
    public ResponseEntity<String> getPassword(@RequestParam("user_id") int user_id){
        try {
            User user=userRepository.findByUserId(user_id);
            if(user!=null){
                return ResponseEntity.ok().body(user.getPassword());
            }else {
                return ResponseEntity.ok().body("用户不存在");
            }
        } catch (Exception e) {
            return ResponseEntity.ok().body("获取用户信息失败"+e.getMessage());
        }
    }
    @PostMapping("/api/update_password")
    public ResponseEntity<String> updatePassword(@RequestBody UserDTO userDTO){
        try {
            User user2=userRepository.findByUserId(userDTO.getUser_id());
            if(user2!=null){
                user2.setPassword(userDTO.getPassword());
                userRepository.save(user2);
                return ResponseEntity.ok().body("用户密码更新完成");
            }else {
                return ResponseEntity.ok().body("用户不存在");
            }
        }catch (Exception e){
            return ResponseEntity.ok().body("更新用户信息失败"+e.getMessage());
        }
    }
    @PostMapping("/api/update_email")
    public ResponseEntity<String> updateEmail(@RequestBody UserDTO userDTO){
        try {
            User user=userRepository.findByUserId(userDTO.getUser_id());
            if(user!=null){
                User user_try=userRepository.findByEmail(userDTO.getEmail());
                if(user_try==null){
                user.setEmail(userDTO.getEmail());
                userRepository.save(user);
                return ResponseEntity.ok().body("用户邮箱更新完成");
                }else {
                    return ResponseEntity.ok().body("用户邮箱已存在，更新失败");
                }
            }else {
                return ResponseEntity.ok().body("用户不存在");
            }
        }catch (Exception e){
            return ResponseEntity.ok().body("更新用户信息失败"+e.getMessage());
        }
    }
    @DeleteMapping("/api/delete_user")
    public ResponseEntity<String> deleteUser(@RequestBody UserDTO userDTO){
        try {
            User user=userRepository.findByUserId(userDTO.getUser_id());
            user.setEmail("#################################12563413316541213312165");
            user.setUsername("账户已注销");
            user.setPassword("fuasoheb1uo2hbruoehurfwbsudewh3urbwfeka");
            user.setAvatarUrl("");
            userRepository.save(user);
            return ResponseEntity.ok("用户删除成功");
        }catch (Exception e)
        {
            return ResponseEntity.ok().body("Failed to delete user: " + e.getMessage());
        }
    }
    @PostMapping("/api/create_follow")
    public ResponseEntity<String> createFollow(@RequestBody FollowDTO followDTO){
        User follower=userRepository.findByUserId(followDTO.getFollower_id());
        User followed=userRepository.findByUserId(followDTO.getFollowed_id());
        Follow follow=new Follow();
        follow.create();
        follow.setFollower(follower);
        follow.setFollowed(followed);
        followRepository.save(follow);
        return ResponseEntity.ok().body("关注成功");
    }
    @GetMapping("/api/get_follow")
    public ResponseEntity<String> getFollow(@RequestParam("follower_id") int follower_id,
                                            @RequestParam("followed_id") int followed_id){
        User follower=userRepository.findByUserId(follower_id);
        User followed=userRepository.findByUserId(followed_id);
        Follow follow=followRepository.findByFollowerAndFollowed(follower,followed);
        if(follow!=null){
            return ResponseEntity.ok().body("ok");
        }
        else {
            return ResponseEntity.ok().body("fail");
        }
    }
    @DeleteMapping("/api/delete_follow")
    public ResponseEntity<String> deleteFollow(@RequestParam("follower_id") int follower_id,
                                               @RequestParam("followed_id") int followed_id){
        User follower=userRepository.findByUserId(follower_id);
        User followed=userRepository.findByUserId(followed_id);
        Follow follow=followRepository.findByFollowerAndFollowed(follower,followed);
        if(follow!=null){
            followRepository.delete(follow);
            return ResponseEntity.ok().body("取消关注成功");
        }else {
            // 如果关注关系不存在，则返回错误信息
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到相关关注关系");
        }
    }
    @GetMapping("/get_follow_count")
    public ResponseEntity<Long[]> getFollowCount(@RequestParam("user_id") int user_id){
        User user=userRepository.findByUserId(user_id);
        long follower_count=followRepository.countByFollower(user);
        long followed_count=followRepository.countByFollowed(user);
        Long[] counts={follower_count,followed_count};
        return ResponseEntity.ok().body(counts);
    }
}
